package com.qkl.upload.publics.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Slf4j
public class HttpUtils {

    private static OkHttpClient httpClient = new OkHttpClient();

    private static MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

    public static HttpResponse<String> postRequestForm(String url,Map<String,String> params){
        if(null == params){
            params = new HashMap<>();
        }
        FormBody.Builder builder = new FormBody.Builder();
        if(ObjectUtils.isNotEmpty(params)){
            Set<Map.Entry<String, String>> set = params.entrySet();
            for(Map.Entry<String, String> entry : set){
                builder.add(entry.getKey(),entry.getValue());
            }
        }
        RequestBody body = builder.build();
        Request request = new Request.Builder().url(url).post(body).addHeader("Content-Type","application/x-www-form-urlencoded").build();
        return httCall(request);
    }

    /**
     *
     * @param url
     * @param jsonBody
     * @return
     */
    public static HttpResponse<String> postRequestJson(String url,Object jsonBody){
        if(null == jsonBody){
            jsonBody = new HashMap<String,String>();
        }

        String json = JSON.toJSONString(jsonBody);
        log.info("http request json={}",json);
        RequestBody body = RequestBody.create(json, MEDIA_TYPE_JSON);
        Request request = new Request.Builder().url(url).post(body).build();
        return httCall(request);
    }

    public static HttpResponse<String> postRequestJson(String url,Map<String,String> headerMap,Object body){
        if(null == body){
            body = new HashMap<String,String>();
        }
        String jsonBody = JSON.toJSONString(body);
        return postRequestJson(url,headerMap,jsonBody);
    }

    public static HttpResponse<String> postRequestJson(String url,Map<String,String> headerMap,String jsonBody){
        if(null == jsonBody){
            jsonBody = "{}";
        }
        RequestBody body = RequestBody.create(jsonBody, MEDIA_TYPE_JSON);

        Request.Builder builder = new Request.Builder();
        setHeaders(builder,headerMap);
        Request request = builder.url(url).post(body).build();
        return httCall(request);
    }

    private static void setHeaders(Request.Builder builder,Map<String,String> headerMap){
        if(!ObjectUtils.isEmpty(headerMap)){
            Set<Map.Entry<String, String>> set = headerMap.entrySet();
            for(Map.Entry<String, String> entry : set){
                String key = entry.getKey();
                String value = entry.getValue();
                log.info("http request header key={},value={}",key,value);
                if(StringUtils.isAnyEmpty(key,value)){
                    continue;
                }
                builder.addHeader(key,value);
            }
        }
    }

    public static HttpResponse<String> getRequest(String url,Map<String,Object> paramMap){
        return getRequest(url,paramMap,null);
    }

    public static HttpResponse<String> getRequest(String url,Map<String,Object> paramMap,Map<String,String> headerMap){
        String params = toURL(paramMap);
        if(!"".equals(params)){
            url = url + "?" + params;
        }
        Request.Builder builder = new Request.Builder();
        setHeaders(builder,headerMap);
        Request request = builder.url(url).get().build();
        return httCall(request);
    }

    private static HttpResponse<String> httCall(Request request){
        long start = System.currentTimeMillis();
        String url = request.url().toString();
        Response response = null;
        String msg = "";
        HttpResponse<String> httpResponse = new HttpResponse<>();
        httpResponse.setSuccess(false);
        String respBody = "";
        try {
            response = httpClient.newCall(request).execute();
            if(response.isSuccessful()){
                respBody = response.body().string();
                httpResponse.setSuccess(true);
                httpResponse.setData(respBody);
            }else {
                log.error("http request fail. message={}",response.body().string());
                msg = "postByJson unSuccessful: code=" + response + ",url=" + url;
            }
        }catch (IOException e){
            msg = "postByJson IOException: " + e ;
        }
        httpResponse.setMsg(msg);
        log.info("http request time=" + (System.currentTimeMillis() - start) + ",url=" + url);
        log.info("http request respBody=" + respBody);
        if(!httpResponse.isSuccess()){
            log.error(msg);
        }
        return httpResponse;
    }

    private static String toURL(Map<String,Object> paramMap){
        StringBuffer params = new StringBuffer();
        if(null != paramMap && !paramMap.isEmpty()) {
            Set<Map.Entry<String, Object>> set = paramMap.entrySet();
            for (Map.Entry<String, Object> entry : set) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (null != key && null != value) {
                    params.append(key).append("=").append(value).append("&");
                }
            }
        }
        if(params.length() > 0){
            params.deleteCharAt(params.length() - 1);
        }
        return params.toString();
    }






    public static void main(String[] args) throws Exception {

        //getUserPhone();
        //Map<String,Object> paramMap = new HashMap<>();
        //paramMap.put("name","su");
        //paramMap.put("code","22222");
        //paramMap.put("index",Integer.valueOf(10));

        //System.out.println(toURL(paramMap));

        //wxLoginVerify();

       // wxToken();
        //System.out.println(System.currentTimeMillis());

    }


}
